package middleware

import (
	"strings"
	"temp/auth"
	"temp/errors"

	"github.com/gin-gonic/gin"
)

func Auth() gin.HandlerFunc {
	return func(c *gin.Context) {
		authorization := c.Request.Header.Get("Authorization")
		str := strings.Split(authorization, " ")
		if len(str) != 2 {
			errors.HandlerAuthError(c)
			c.Abort()
			return
		}
		token := str[1]
		if token == "" {
			errors.HandlerAuthError(c)
			c.Abort()
			return
		}

		if v := auth.ValidateToken(token); !v {
			errors.HandlerAuthError(c)
			c.Abort()
		}
		c.Next()
	}
}
